package com.jty.module_user.ui.fragment

import android.os.Build
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ThreadUtils.runOnUiThread
import com.czl.lib_base.config.AppConstants
import com.jty.lib_base.base.BaseFragment
import com.jty.lib_base.base.mApplication
import com.jty.lib_base.utils.AppInstallUtil
import com.jty.lib_base.utils.DownloadUtil
import com.jty.lib_base.utils.getDowApkPath
import com.jty.module_user.BR
import com.jty.module_user.R
import com.jty.module_user.databinding.UserFragmentUpdateBinding
import com.jty.module_user.viewmodel.UpdateViewModel
import com.orhanobut.logger.Logger
import java.io.File


@Route(path = AppConstants.Router.User.F_UPDATE)
class UserUpdateFragment : BaseFragment<UserFragmentUpdateBinding, UpdateViewModel>() {

    var isDowing = false
    var mDownloadUrl = ""
    var isSuccess = false
    var mPath = ""
    override fun initContentView(): Int {
        return R.layout.user_fragment_update
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }




    override fun initData() {
        super.initData()
        viewModel.tvTitle.set("版本更新")

        val version = arguments?.getString("version", "")?:""
        val downloadUrl = arguments?.getString("downloadUrl", "")?:""
        val apkSize = arguments?.getInt("apkSize", 0)?:0
        mDownloadUrl = downloadUrl
        viewModel.setParams(version, downloadUrl, apkSize)

    }

    override fun initViewObservable() {
        viewModel.uc.onClickDowLoad.observe(this){
            binding.btnDownload.visibility = View.INVISIBLE
            binding.tvSize.visibility = View.VISIBLE
            binding.tvTag.visibility = View.VISIBLE
            binding.progressPbBar.visibility = View.VISIBLE

            update()
        }

        viewModel.uc.onFinish.observe(this) {
            onBackClick()
        }


    }


    override fun onBackPressedSupport(): Boolean {
        //return super.onBackPressedSupport()
        onBackClick()
        return true
    }

    private fun onBackClick() {
        if(isDowing) {
            showNormalToast("正在下载，不能退出")
        } else {
            requireActivity().finish()
        }
    }

    override fun onResume() {
        super.onResume()
        if(isSuccess) {
            AppInstallUtil.installApk(mApplication, mPath)
            isSuccess = false
        }
    }

    /*override fun onPause() {
        super.onPause()

        refreshFailUI()
        if(isDowing) {
            DownloadUtil.get().cancelTag(mDowloadUrl)
        }
    }*/

    override fun onDestroyView() {
        super.onDestroyView()

        refreshFailUI()
        if(isDowing) {
            DownloadUtil.get().cancelTag(mDownloadUrl)
        }
    }

    fun refreshFailUI(){
        binding.btnDownload.visibility = View.VISIBLE
        binding.tvSize.visibility = View.INVISIBLE
        binding.tvTag.visibility = View.INVISIBLE
        binding.progressPbBar.visibility = View.INVISIBLE

        binding.progressPbBar.progress = 0
        viewModel.updateDowloadSize(0, 0, 0)
    }

    /**
     * 进行更新操作
     */
    private fun update() {
        val apkFilePath = getDowApkPath(
            viewModel.model.getUserId()!!,
            "apk",
            "" + FileUtils.getFileName(mDownloadUrl),
        )!!
        val apkFile = File(apkFilePath)
        if (apkFile.exists()) {
            apkFile.delete()
        }
        download(apkFilePath)
    }


    fun download(apkFilePath: String) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val hasInstallPermission: Boolean =
                AppInstallUtil.isHasInstallPermissionWithO(mApplication)
            if (!hasInstallPermission) {
                AppInstallUtil.startInstallPermissionSettingActivity(mApplication)
                refreshFailUI()
                return
            }
        }
        Logger.i("download url ==$mDownloadUrl")
        // url="https://jtysunbox.oss-cn-beijing.aliyuncs.com/application/SunboxApp/penbox_goline_v1.0.7.apk";
        isDowing = true
        DownloadUtil.get().download(requireActivity(), mDownloadUrl, FileUtils.getDirName(apkFilePath), object : DownloadUtil.OnDownloadListener {
            override fun onDownloadSuccess(path: String?) {
                runOnUiThread(Runnable {
                    isDowing = false
                    isSuccess = true
                    mPath = path!!
                    AppInstallUtil.installApk(mApplication, path)
                    refreshFailUI()
                })
            }

            override fun onDownloading(sum: Int, total: Int, progress: Int) {
                runOnUiThread(Runnable {
                    binding.progressPbBar.progress = progress
                    viewModel.updateDowloadSize(sum, total, progress)
                })

            }

            override fun onDownloadFailed() {
                runOnUiThread(Runnable {
                    isDowing = false
                    refreshFailUI()
                })
            }

            override fun onNetwork(isNetwork: Boolean) {
                runOnUiThread(Runnable {
                    if (!isNetwork) {
                        showNormalToast("请检查网络是否连接")
                        isDowing = false
                        refreshFailUI()
                    }
                })
            }
        })
    }
}